<?php
/**
 * 产品 <==> 分类 关联
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/11/28
 * @copyright PanxSoft Inc.
 */
namespace App\Models\Products;

use App\Models\Concerns\HasCompositePrimaryKey;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * @method static self filterCategory(int|null $category_id)
 * @method static self filterStore(int $store_id)
 */
class ProductToCategory extends Model
{
    use HasCompositePrimaryKey;

    protected $table = 'product_to_category';

    protected $guarded = [];

    protected $primaryKey = ['product_id', 'category_id'];

    public $timestamps = false;

    public $incrementing = false;

    /**
     * @used-by filterCategory
     *
     * @param Builder $query
     * @param int|null $category_id
     */
    public function scopeFilterCategory(Builder $query, ?int $category_id): void
    {
        if ($category_id) {
            $query->where('category_id', $category_id);
        }
    }

    /**
     * @used-by filterStore
     *
     * @param Builder $query
     * @param int $store_id
     */
    public function scopeFilterStore(Builder $query, int $store_id): void
    {
        $prod_ids = (new ProductToStore)
            ->where(compact('store_id'))
            ->pluck('product_id');

        $query->whereIn('product_id', $prod_ids);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function productByOnSale()
    {
        /** @var Product|\Illuminate\Database\Eloquent\Relations\BelongsTo $product */
        $product = $this->belongsTo(Product::class, 'product_id', 'product_id');

        return $product->filterOnshelf();
    }
}
